package com.sdw.message.dao;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import com.sdw.message.dao.base.DataBase;
import com.sdw.message.dao.base.DataReader;
import com.sdw.message.pojo.Message;

@Repository("messageDao")
public class MessageDao {

	@Resource
	private DataBase messageDatabase;
	
	public Iterable<Message> getLastTopMessage(int top){
		String sql = "select top " + top + " id, title, cont, username, score, needreplynum, replynum, isreply, createtime, modifytime, department"
				+ " from [dbo].[sys_message] order by modifytime desc";
		
		DataReader reader = null;
		List<Message> list = new ArrayList<Message>();
		try{
			reader = this.messageDatabase.executeQuery(sql);
			while(reader.next()){
				list.add(this.conver(reader));
			}
			return list;
		}finally{
			if(reader != null){
				reader.close();
			}
		}
	}
	
	private Message conver(DataReader reader){
		int index = 1;
		Message message = new Message();
		
		message.setId(reader.getLong(index++));
		message.setTitle(reader.getString(index++));
		message.setCont(reader.getString(index++));
		message.setUserName(reader.getString(index++));
		message.setScore(reader.getByte(index++));
		message.setNeedReplyNum(reader.getByte(index++));
		message.setReplyNum(reader.getByte(index++));
		message.setReply(reader.getBoolean(index++));
		message.setCreateTime(reader.getDate(index++));
		message.setModifyTime(reader.getDate(index++));
		message.setDepartment(reader.getString(index++));
		
		return message;
	}
}
